<template>
    <van-button
      v-if="!isFollowed"
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="followLoading"
      @click="onFollow"
      >关注</van-button
    >
    <van-button
      v-else
      class="follow-btn"
      round
      :loading="followLoading"
      size="small"
      @click="onFollow"
      >已关注</van-button
    >
</template>
<script>
import {AddFollow,DeleteFollow } from "@/api/user"
export default {
  name:"followUser",
  data() {
    return {
        followLoading:false // 关注加载中按钮
    };
  },
    //   自定义v-model数据的名称
  model:{
      prop:'isFollowed',  // 默认是value
      event:'update-is_followed'  // 默认是input
  },
  props: {
    isFollowed: {
      type: Boolean,
      default: true,
    },
    userId:{
        type:[Number,String,Object],
        required:true
    }
  },
  methods: {
    // 取消、添加关注
    async onFollow() {
      this.followLoading = true;
      try {
        // 判断是否关注了
        if (this.isFollowed) {
          // 已经关注，则取消
          await DeleteFollow(this.userId);
        } else {
          // 没关注，则要关注
          await AddFollow(this.userId);
        }
        // 通知父组件 更新按钮状态
        this.$emit('update-is_followed',!this.isFollowed)
      } catch (error) {
          console.log(error);
        let message = "操作失败，请重试！";
        if (error.response && error.response.status === 400) {
          message = "你不能关注你自己";
        }
        this.$toast.fail(message);
      }
      this.followLoading = false;
    },
  },
  components: {},
};
</script>
<style scoped>
</style>